﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.IO.Extensions;
using Abp.UI;
using Abp.Web.Models;
using MVlog.DemoUiComponents.Dto;
using MVlog.Storage;
using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace MVlog.Web.Controllers
{
    [AbpMvcAuthorize]
    public class UploadController:AbpZeroTemplateControllerBase
    {
        private IHostingEnvironment _hostingEnvironment;

        public UploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpPost]
        public async Task<JsonResult> UploadFile()
        {
            try
            {
                var files = Request.Form.Files;

                //Check input
                if (files == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                //List<UploadFileOutput> filesOutput = new List<UploadFileOutput>();
                string filePath = "";
                foreach (var file in files)
                {
                    //不限制文件大小，最大1G
                    //if (file.Length > 1048576) //1MB
                    //{
                    //    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                    //}

                    //byte[] fileBytes;
                    using (var stream = file.OpenReadStream())
                    {
                        //fileBytes = stream.GetAllBytes();
                        var Path = "\\Files\\"+ DateTime.Now.ToString("yyyyMMddhhmmss") + file.FileName;
                        var uploadPath = _hostingEnvironment.WebRootPath + Path;
                        StreamWriter sw = new StreamWriter(uploadPath);
                        await stream.CopyToAsync(sw.BaseStream);
                        sw.Flush();
                        sw.Close();
                        filePath = Path;
                    }

                    //var fileObject = new BinaryObject(null, fileBytes);
                    //await _binaryObjectManager.SaveAsync(fileObject);

                    //filesOutput.Add(new UploadFileOutput
                    //{
                    //    Id = fileObject.Id,
                    //    FileName = file.FileName
                    //});

                }

                return Json(new AjaxResponse(filePath));
            }
            catch (UserFriendlyException ex)
            {
                return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
            }
        }
    }
}
